const md5 = require("md5");
const userModel = require("../models/userModel");

exports.addUser = async function (userObj) {
  userObj.userPwd = md5(userObj.userPwd);
  const ins = await userModel.create(userObj);
  return ins.toJSON();
};

exports.deleteUser = async function (id) {
  const ins = await userModel.destroy({
    where: {
      id,
    },
  });
  return ins.toJSON();
};

exports.updateUser = async function (id, userObj) {
  userObj.userPwd = md5(userObj.userPwd);
  const ins = userModel.update(userObj, {
    where: {
      id,
    },
  });
  return ins.toJSON();
};

exports.findUser = async function (id) {
  const ins = await userModel.findByPk(id);
  return ins.toJSON();
};

exports.login = async function (userObj) {
  const ins = await userModel.findOne({
    where: {
      userId: userObj.userId,
      userPwd: md5(userObj.userPwd),
    },
  });
  if (ins) {
    return ins.toJSON();
  } else {
    return null;
  }
};
